<template>
    <div class="ele-body">
      <el-card>
        <div class="content_hangs_title">
          <button v-for="(item,index) in timeData" :key="index" @click="inde=index;initTime(item.id,true)" :class="inde==index?'chart_btn actives':'chart_btn'">{{item.name}}</button>
          <el-date-picker @change="initTime(null,true)" v-model="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
          <span style="float:right">
            <button @click="reportexcel" type="button" class="
                      el-button
                      ele-btn-icon
                      el-button--primary el-button--medium
                      button_dc
                    ">
                    <i class="el-icon-upload2"></i><span>导 出 </span>
            </button>
          </span>
        </div>
      </el-card>
      <el-card>
        <div id="myChart" :style="{width: '100%', height: '350px'}"></div>
      </el-card>
      <el-card style="margin-top:15px;margin-bottom:15px">
        <ele-pro-table ref="table" row-key="id" :columns="columns" :datasource="datasource" stripe border max-height="450" :default-expand-all="false" :need-page="false" show-summary :summary-method="getSummaries"  >
         <!-- 表头工具栏 -->
         <template slot="toolbar">
            <span style="font-size:18px;font-weight:bold;color:black;">销售人员订单统计数据</span>
          </template>
        </ele-pro-table>
      </el-card>
      <ExportDialog ref="ExportDialog"></ExportDialog>
    </div>
  </template>
  <script>
  import moment from "moment"
  import ExportDialog from '@/components/Excel/ExportDialog'
  import { QuerySaleAnalysisView } from '@/api/analysismanager/saleanaylsis'
  export default {
    name: "SaleAnalysis",
    components: {ExportDialog},
    data() {
      return {
        timeData: [{ id: '0', name: '今日' }, { id: '1', name: '本月' }, { id: '2', name: '本年' }],
        select: '',
        data: [],
        where: {},
        inde: 1,
        date: '',
        columns: [
            { columnKey: 'index', type: 'index', width: 55, align: 'center', showOverflowTooltip: true, fixed: 'left', label:'序号', },
            { prop: 'orderTime', label: '订单日期', sortable: 'gradeId', showOverflowTooltip: true, formatter: (row, column, cellValue) => {
                return this.$util.toDateString(cellValue,"YYYY-MM-DD");
              }
            },
            { prop: 'orderNo', label: '订单号', sortable: 'orderNo', showOverflowTooltip: true, },
            { prop: 'productNum', label: '产品数量', sortable: 'productNum', showOverflowTooltip: true, },
            { prop: 'totalPrice', label: '订单金额', sortable: 'totalPrice', showOverflowTooltip: true, },
            { prop: 'disPrice', label: '优惠金额',  showOverflowTooltip: true, },
            { prop: 'fullDisPrice', label: '满减优惠',  showOverflowTooltip: true,},
            { prop: 'couponPrice', label: '优惠券抵扣',  showOverflowTooltip: true, },
            { prop: 'recPrice', label: '应收金额', sortable: 'recPrice', showOverflowTooltip: true, },
            { prop: 'returnPrice', label: '退货金额',  showOverflowTooltip: true, },
            { prop: 'customerName', label: '客户名称', sortable: 'customerName', showOverflowTooltip: true, },
            { prop: 'saleName', label: '所属业务', sortable: 'saleName', showOverflowTooltip: true, },
          ],
        exportList: [
          { keys: 'orderNo', name: '订单号',  status: true, },
          { keys: 'productNum', name: '产品数量', status: true, },
          { keys: 'totalPrice', name: '订单金额',  status: true, },
          { keys: 'disPrice', name: '优惠金额',  status: true, },
          { keys: 'fullDisPrice', name: '满减优惠', status: true, },
          { keys: 'couponPrice', name: '优惠券抵扣', status: true, },
          { keys: 'recPrice', name: '应收金额', status: true, },
          { keys: 'returnPrice', name: '退货金额', status: true, },
          { keys: 'customerName', name: '客户名称', status: true, },
          { keys: 'saleName', name: '所属业务', status: true, },
        ]
      }
    },
    mounted() {
      this.reload(null);
    },
    methods: {
      /* 表格数据源 */
      async datasource(params) {
        this.initTime(this.inde, false);
        if(params.where==null||params.where==undefined){
            params.where.sdate = this.where.sDate;
            params.where.edate = this.where.eDate;
        }

        let data = await QuerySaleAnalysisView(params.where);

        this.drawLine(data.saleNameAnalysisViews);
        return {
          list:data.saleAnalysisViews,
          count:data.saleAnalysisViews.length,
        };
      },
      /* 导出 */
      reportexcel() {
        this.initTime(this.inde, false);
        
        let obj = {
          sdate: this.where.sDate,
          edate: this.where.eDate,
        };
        //加载进度条
        const loading = this.$loading({ lock: true });
        //查询数据
        QuerySaleAnalysisView(obj)
          .then((data) => {
            loading.close();
            this.$refs.ExportDialog.showEdits = true
            this.$refs.ExportDialog.checkList = this.exportList
            this.$refs.ExportDialog.titleName = "销售人员业绩统计"
            this.$refs.ExportDialog.dataList = data.saleAnalysisViews;
          })
          .catch((e) => {
            loading.close();
            this.$message.error(e.message);
          });
      },
      //刷新表格
      reload(where) {
        
        if(where){
          this.where.sDate = where.sDate;
          this.where.edate = where.eDate;
        }
       
        this.$refs.table.reload({ where: this.where });
      },
      
      drawLine(data) {
        var a = data && data.slice(0, 5)
        var b = []
        var c = []
        if (a) {
          b = a.reduce((e, item) => [...e, item.saleName], [])
          c = a.reduce((e, item) => [...e, item.totalPrice], [])
        }
        // 基于准备好的dom，初始化echarts实例
        let myChart = this.$echarts.init(document.getElementById('myChart'))
        // 绘制图表
        myChart.setOption({
          title: {
            text: '销售人员业绩统计数据'
          },
          borderColor: '#ccc',
          axisLabel: {
            color: 'black'
          },
  
          tooltip: {},
          legend: {
            data: ['订单金额排名',]
          },
          xAxis: {
            axisLine: {
              lineStyle: {
                color: '#ccc',
                width: 1,
              }
            },
            barwidth: 10,
            data: b,
            axisLabel: {
              show: true,
              textStyle: {
                fontSize: 15
              }
            },
            axisTick: {       //x轴刻度线
              show: false
            },
          },
          yAxis: {
            type: 'value',
            axisLine: {
              lineStyle: {
                color: '#ccc',
                width: 1,
              }
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              }
            },
            data: ["0", "0.5", "1", "1.5", "2"],
            axisLabel: {
              show: true,
              textStyle: {
                fontSize: 15
              }
            },
            axisTick: {       //y轴刻度线
              show: false
            },
          },
  
          series: [{
            name: '订单金额',
            type: 'bar',
            data: c,
            itemStyle: {
              normal: {
                lineStyle: {
                  color: '#FF4160'
                },
                color: function (params) {
                  // 给出颜色组
                  var colorList = ['#00CC75', '#DFC02E', '#3E61D8', '#DF672E', '#964FD6'];
                  return colorList[params.dataIndex]
                },
              }
            },
            barWidth: 60,
          },
          ]
        });
      },
      //选中日、月、年后格式化时间
      initTime(timeId, flag) {
        var sDate = "";
        var eDate = "";
        if (timeId != null) {
          eDate = moment().format("YYYY-MM-DD HH:mm:ss")
          if (timeId == 0) {
            //今日
            sDate = moment().startOf('day').format('YYYY-MM-DD HH:mm:ss')
            this.date = [sDate, eDate]
          } else if (timeId == 1) {
            //本月
            sDate = moment().startOf('months').format('YYYY-MM-DD HH:mm:ss')
            eDate = moment().endOf('months').format('YYYY-MM-DD 23:59:59')
            this.date = [sDate, eDate]
          } else if (timeId == 2) {
            //本年
            sDate = moment().startOf('years').format('YYYY-MM-DD HH:mm:ss')
            eDate = moment().endOf('years').format("YYYY-MM-DD 23:59:59")
            this.date = [sDate, eDate]
          }
        } else {
          sDate = this.date[0];
          eDate = this.date[1];
        }
        this.where.sDate = sDate;
        this.where.eDate = eDate;

        if (flag) {
          this.reload(this.where);
        }
      },

      /* 合计 */
      getSummaries(param){
        const sums = [];
        sums[0] = '合计' ;
        const { columns, data } = param;
        columns.forEach((column, index) => {
          if(index ==3 || index ==4 || index ==5|| index ==6|| index ==7|| index ==8|| index ==9){
            sums[index] = 0;
            const values = data.map(item => Number(item[column.property]));
            if (values.some(value => !isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0);
              sums[index]  = Number(sums[index]).toFixed(2);
            }
          }
        });
        return sums;
      },
    }
  }
  </script>
  <style lang="scss" scoped>
  .top_dai {
    width: 50px;
    height: 25px;
    cursor: pointer;
    text-align: center;
    line-height: 25px;
    border-radius: 3px;
    display: inline-block;
    border: 1px solid #ccc;
    margin-left: 20px;
  }
  .active {
    border: 1px solid #fe920f;
    color: #fff;
    background: #fe920f;
  }
  .aa {
    display: flex;
    justify-content: space-around;
  }
  .chart_btn {
    width: 5%;
    padding: 15px;
    padding: 5px 10px;
    height: 36px;
    margin: 0 8px;
    // background-color: #1b418b;
    // border: 1px solid #2c5397;
    // border-radius: 6px;
    // color: #fff;
    cursor: pointer;
    border: 1px solid #ccc;
  }
  .actives {
    border: 1px solid #fdb600;
    color: #fdb600;
  }
  </style>